package com.ifudata.dataexpert.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ifudata.dataexpert.constants.SmsConstants;
import com.ifudata.dataexpert.constants.SmsEnums;
import com.ifudata.dataexpert.model.LoginParam;
import com.ifudata.dataexpert.model.ResultMap;
import com.ifudata.dataexpert.util.JWTUtil;
import com.ifudata.dvp.app.api.app.interfaces.IAppManageSV;
import com.ifudata.dvp.app.api.app.param.CollectAppMenusRequest;
import com.ifudata.dvp.base.vo.BaseResponse;
import com.ifudata.dvp.sdk.dubbo.util.DubboConsumerFactory;
import com.ifudata.dvp.sdk.util.RedisUtil;
import com.ifudata.dvp.sys.api.staff.interfaces.ISysStaffQuerySV;
import com.ifudata.dvp.sys.api.staff.param.StaffQueryResponse;
import com.ifudata.dvp.sys.api.staff.param.ValidStaffPwdRequest;
import com.ifudata.dvp.sys.api.staffintegrity.interfaces.ISysStaffIntegrityQuerySV;
import com.ifudata.dvp.sys.api.staffintegrity.param.StaffIntegrityQueryResponse;

/**
 *
 * @Author libing
 * @Description
 * @Date 2018-04-29
 * @Time 13:20
 */
@RestController
public class LoginController {
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@PostMapping("/validToken")
    @Produces(MediaType.APPLICATION_JSON)
	@ResponseBody
	public ResultMap validToken(){
		log.debug("validToken");
		ResultMap resultMap = new ResultMap(true);
		JSONObject object = new JSONObject();
		try{
			StaffQueryResponse staff = resultMap.getStaff();
			log.debug("validToken staff: "+JSON.toJSONString(staff));
			if( staff==null||staff.getStaffNo()==null||staff.getStaffId()==null ){
				resultMap.code(SmsConstants.ResCode.CODE_501);
			}else{
				String json = JSON.toJSONString(staff);
				object.put("USERINFO", json);
				RedisUtil.set("USERINFO_" + staff.getStaffNo(), json); // 把用户信息放入redis
				
				ISysStaffIntegrityQuerySV sv = DubboConsumerFactory.getService(ISysStaffIntegrityQuerySV.class);
				StaffIntegrityQueryResponse staffRes = sv.queryStaffIntegrityInfo(staff.getStaffId());
				if (staffRes != null) {
					object.put("USERPRIVILEGED", JSON.toJSONString(staffRes.getStaffIntegrityVo()));
					RedisUtil.set("USERPRIVILEGED_" + staff.getStaffNo(), JSON.toJSONString(staffRes)); // 把用户权限信息放入redis
				}
				// 用户收藏
    			object.put("USER_COLLECT", getCollectMenu(staff.getStaffId()));
				resultMap.success().dataJson(object);
			}
		}catch( Exception e ){
			log.error("validToken 系统异常，异常信息{}", e);
			resultMap.code(SmsConstants.ResCode.CODE_501);
		}
		return resultMap;
	}
	
	/**
	 * 用户登录验证 返回token
	 * @param username
	 * @param password
	 * @return
	 */
    @PostMapping("/login")
    @Produces(MediaType.APPLICATION_JSON)
    @ResponseBody
    public ResultMap login(@RequestBody LoginParam loginParam, HttpServletRequest request) {
    	log.debug("login/loginParam:{}", loginParam.toString());
    	ResultMap resultMap = new ResultMap();
    	JSONObject object = new JSONObject();
    	try {
			//将用户角色存redis
    		List<String> roleList = new ArrayList<String>();
    		roleList.add("admin");
    		roleList.add("user");
    		
    		ISysStaffQuerySV sv = DubboConsumerFactory.getService(ISysStaffQuerySV.class);
    		ValidStaffPwdRequest valid = new ValidStaffPwdRequest();
    		valid.setStaffNo(loginParam.getLoginCode());
    		valid.setPassword(loginParam.getPassword());
    		valid.setToken("2ICiu@Tf");
    		BaseResponse response = sv.validateStaffPwd(valid);
    		
    		if( response.getResponseHeader().isSuccess() ){
    			RedisUtil.hset(SmsEnums.RedisKey.RedisKeyCode.SYS_USER_INFO.toString(), loginParam.getLoginCode(), JSON.toJSONString(roleList));
    			
    			ISysStaffQuerySV staffSV = DubboConsumerFactory.getService(ISysStaffQuerySV.class);
    			StaffQueryResponse staff = staffSV.queryStaffByNo(loginParam.getLoginCode());
    			if (staff != null) {
    				String json = JSON.toJSONString(staff);
    				object.put("USERINFO", json);
    				RedisUtil.set("USERINFO_" + staff.getStaffNo(), json); // 把用户信息放入redis
    			
    				ISysStaffIntegrityQuerySV sysStaffIntegrityQuerySV = DubboConsumerFactory.getService(ISysStaffIntegrityQuerySV.class);
    				StaffIntegrityQueryResponse staffRes = sysStaffIntegrityQuerySV.queryStaffIntegrityInfo(staff.getStaffId());
    				if (staffRes != null) {
    					object.put("USERPRIVILEGED", JSON.toJSONString(staffRes.getStaffIntegrityVo()));
    					RedisUtil.set("USERPRIVILEGED_" + staff.getStaffNo(), JSON.toJSONString(staffRes)); // 把用户权限信息放入redis
    				}
    			}
    			
    			// 用户收藏
    			object.put("USER_COLLECT", getCollectMenu(staff.getStaffId()));
    			
    			resultMap.success().token(JWTUtil.createToken(JSON.toJSONString(staff))).message("登录成功").dataJson(object);    			
    		}else{
    			resultMap.fail().message(response.getResponseHeader().getResultMessage());
    		}
		} catch (Exception e) {
			log.error("login 系统异常，异常信息{}",e);
			resultMap.exception().message(SmsConstants.ResMsg.FAILED);
		}
	    return resultMap;
    }
    
    @RequestMapping(path = "/unauthorized/{message}")
    public ResultMap unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
    	log.debug("login/message:{}", message);
    	ResultMap resultMap = new ResultMap();
    	resultMap.code(SmsConstants.ResCode.CODE_501).message(message);
    	return resultMap;
    }

    /**
     * 获取用户收藏
     * @param staffId
     * @return
     */
    private String getCollectMenu(Long staffId) {
    	JSONArray re = new JSONArray();
		try {
			CollectAppMenusRequest requset = new CollectAppMenusRequest();
			requset.setStaffId(staffId);
			IAppManageSV sv = DubboConsumerFactory.getService(IAppManageSV.class);
			String res = sv.queryCollectAppMenus(requset);
			
			JSONArray arr = JSONArray.parseArray(res);
			JSONObject menu;
			for( int i=0; i<arr.size(); i++ ){
				menu = arr.getJSONObject(i);
				if( menu.containsKey("MENU_ID") ){
					re.add(menu.get("MENU_ID"));					
				}
			}
		} catch (Exception e) {
			log.error("getData 系统异常，异常信息{}", e);
		}
		return re.toJSONString();
	}
}
